package leetcode.prefixSum.common;

import java.util.HashMap;
import java.util.Map;

public class PrefixSumUtils {
    public static boolean checkSubarraySum(int[] nums, int k) {
        if (nums.length < 2) {
            return false;
        }
        int[] prefixSum = new int[nums.length + 1];
        Map<Integer, Integer> map = new HashMap<>();
        prefixSum[0] = 0;
        map.put(0, -1);
        for (int i = 1; i < nums.length + 1; i++) {
            prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
            int mod = prefixSum[i] % k;
            Integer lastPos = map.get(mod);
            if (lastPos != null && i - 1 - lastPos >= 2) {
                return true;
            }
            map.putIfAbsent(mod, i - 1);
        }
        return false;
    }

    public static int maxSubArrayLen(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int lastSum = 0;
        map.putIfAbsent(0, -1);
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = lastSum + nums[i];
            Integer index = map.getOrDefault(sum - k, -2);
            if (index >= -1) {
                result = Math.max(result, i - index);
            }
            map.putIfAbsent(sum, i);
            lastSum = sum;
        }
        return result;
    }

    public static int waysToMakeFair(int[] nums) {
        // 前缀和
        int oddPrefixSum = 0, evenPrefixSum = 0;
        // 后缀和
        int oddSuffixSum = 0, evenSuffixSum = 0;
        for (int i = 0; i < nums.length; ++i) {
            if ((i & 1) != 0) {
                oddSuffixSum += nums[i];
            } else {
                evenSuffixSum += nums[i];
            }
        }
        int res = 0;
        for (int i = 0; i < nums.length; ++i) {
            // 删除当前数
            if ((i & 1) != 0) {
                oddSuffixSum -= nums[i];
            } else {
                evenSuffixSum -= nums[i];
            }
            // 判断删除后的前后缀和是否符合要求
            if (oddPrefixSum + evenSuffixSum == oddSuffixSum + evenPrefixSum) {
                ++res;
            }
            // 恢复当前数
            if ((i & 1) != 0) {
                oddPrefixSum += nums[i];
            } else {
                evenPrefixSum += nums[i];
            }
        }
        return res;
    }

    public static int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] prefix = new int[n];
        int[] suffix = new int[n];
        prefix[0] = nums[0];
        for (int i = 1; i < n; i++) {
            prefix[i] = prefix[i - 1] * nums[i];
        }
        suffix[n - 1] = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            suffix[i] = suffix[i + 1] * nums[i];
        }
        int[] ans = new int[n];
        ans[0] = suffix[1];
        ans[n - 1] = prefix[n - 2];
        for (int i = 1; i <= n - 2; i++) {
            ans[i] = prefix[i - 1] * suffix[i + 1];
        }
        return ans;
    }
}
